package pacote;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;

public class CamadaDeEnlace extends Thread {
	private DatagramSocket socket;
	private ArrayList<Datagrama> inBuffer;
	
	public CamadaDeEnlace(Mac mac) {
		try {
			inBuffer = new ArrayList<Datagrama>();
			
			socket = new DatagramSocket(mac.getPorta());
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		byte[] receiveData = new byte[11200];
		while (true) {
			try {
				DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
				socket.receive(receivePacket);
				
				String string_frame = new String(receivePacket.getData());
				Frame novo_frame = new Frame();
				novo_frame.stringToFrame(string_frame);
				
				Datagrama novo_datagrama = novo_frame.getDatagrama();
				
				adicionaNoBuffer(novo_datagrama);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private synchronized void adicionaNoBuffer(Datagrama novo_datagrama) {
		inBuffer.add(novo_datagrama);
	}

	public void sendDatagrama(Datagrama datagrama, Mac mac_origem, Mac mac_destino) {
		byte[] sendData = new byte[11200];
		
		Frame frame = new Frame(mac_destino, mac_origem, datagrama);
		InetAddress IPAddress;
		try {
			IPAddress = InetAddress.getByName("localhost");
			int port = frame.getMac_destino().getPorta();
			String capitalizedSentence = frame.getFrameString();
			sendData = capitalizedSentence.getBytes();
			
			DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length, IPAddress, port);
			socket.send(sendPacket);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized boolean temDatagrama() {
		return !inBuffer.isEmpty();
	}
	
	public synchronized Datagrama getDatagrama(){
		Datagrama datagrama = inBuffer.get(0);
		inBuffer.remove(0);
		return datagrama;
	}
}
